<?php
/**
 * Introduction: 配送地区
 * @author: 杨陈鹏
 * @date: 2016/4/11 09:38
 * @email: yangchenpeng@cdlinglu.com
 */

namespace Admin\Controller\Logistics;


use Common\Controller\Admin\CommonController;

class DistributionAreaController extends CommonController
{

    /**
     * Introduction: 配送地区列表
     * @author: 杨陈鹏
     * @date: 2016/4/11 09:38
     * @email: yangchenpeng@cdlinglu.com
     */
    public function lists()
    {

        $logic = D('Common/Area', 'Logic');

        $data = $logic::getData('level < 4', 'id,name,pid');

        foreach ($data as $k => $v) {

            $datas[$v['id']] = $v;

        }

        $sell_area_logic = D('Common/SellArea', 'Logic');

        $this->store_id = 1; //为1时为后台发布

        $this->areas = $sell_area_logic::getSellAreaData($this->store_id);

        $this->other = $data = generateTree($datas);

        $group = A('Basic/Group');

        $this->data = $group::getHtmlTree($data, $this->areas, 0, ['name' => 'name', 'id' => 'id', 'pid' => 'pid', 'child' => 'child']);

        $this->display();

    }

    /**
     * Introduction: 保存区域数据
     * @author: 杨陈鹏
     * @date: 2016/4/11 09:38
     * @email: yangchenpeng@cdlinglu.com  //post请求数据太大    实现分批请求
     */
    public function save()
    {


        $data = I('post.data');

        $send = I('post.send');

        if ($send == 'only') {

            $logic = D('Common/SellArea', 'Logic');

            $this->ajaxReturn($logic::save($data));

        } else if ($send == 'end') {

            $nums = I('post.nums');

            $areas = [];

            for ($i = 1; $i <= $nums; $i++) {

                $area = file_get_contents(CACHE_PATH . 'areas' . $i . '.txt');

                unlink(CACHE_PATH . 'areas' . $i . '.txt');

                $areas = array_merge($areas, unserialize($area));

            }
            $data['areas'] = $areas;
            $data['store_id'] = I('post.store_id');

            $logic = D('Common/SellArea', 'Logic');

            $this->ajaxReturn($logic::save($data));


        } else {

            if(!is_dir(CACHE_PATH))
                mkdir(CACHE_PATH,0777,true);

            file_put_contents(CACHE_PATH . 'areas' . $send . '.txt', serialize($data['areas']));

            $this->ajaxReturn(['code' => 100, 'data' => $data['areas']]);

        }

    }
}